package com.xiguaji.tiktok.v1.user.validate;

import com.xiguaji.boot.toolkit.HttpUtil;
import com.xiguaji.boot.toolkit.JsonUtil;
import com.xiguaji.tiktok.utils.DESEncryptUtil;
import com.xiguaji.tiktok.utils.jwt.JwtUser;
import com.xiguaji.tiktok.utils.jwt.JwtUtil;
import com.xiguaji.tiktok.v1.tiktok.permission.repository.UserRoleRepository;
import com.xiguaji.tiktok.v1.user.model.User;
import io.micrometer.core.instrument.util.StringUtils;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import java.util.Date;

@Component
@Slf4j
public class UserHandler {
    @Value("${jwt.head}")
    public String authorized;
    @Autowired
    JwtUtil jwtUtil;
    @Autowired
    public UserRoleRepository userRoleRepository;
    @Value("${server.servlet.session.cookie.domain}")
    public String domain;
    @Autowired
    public RedisTemplate<String,String> redisTemplate;



    public User getUser(){
        return getMyUserInfo().getUser();
    }

    public UserInfo getMyUserInfo(){
        UserInfo userInfo = new UserInfo();
        String token = HttpUtil.getCookie(authorized);
        // 置空token
        if(clearCookieByToken()){
            token = "";
        }
        // 国内网站跳入认证
        String authId = HttpUtil.getRequest().getParameter(authorized);
        if(null != authId && StringUtil.isNullOrEmpty(HttpUtil.getCookie(authorized))){
            long id = decrypt(authId);

            if(id > 0){
                token = redisTemplate.opsForValue().get(String.valueOf(id));

                if(!StringUtils.isEmpty(token)){
                    if(token.equals(redisTemplate.opsForValue().get(authId))){
                        setLoginCookie(token);
                        redisTemplate.delete(authId);
                    }
                }
            }
        }


        if(StringUtils.isEmpty(token)){
            userInfo.setCode(-1);
            userInfo.setMsg("未登入");
            return userInfo;
        }
        JwtUser jwtUser = jwtUtil.getJwtUser(token);

        if(null == jwtUser){
            userInfo.setCode(-2);
            userInfo.setMsg("非法token");
            return userInfo;
        }
        User user = JsonUtil.jsonParse(User.class, JsonUtil.parseJson(jwtUser.getUser()));

        if(!token.equals(getRedisCashToke(user.getId()))){
            userInfo.setCode(-2);
            userInfo.setMsg("token失效");
            return userInfo;
        }
        userInfo.setUser(user);
        return userInfo;
    }
    // 清除cookie
    public Boolean clearCookieByToken(){
        String token = HttpUtil.getCookie(authorized);

        if(!StringUtils.isEmpty(token)){
            JwtUser jwtUser = jwtUtil.getJwtUser(token);
            if(null != jwtUser){
                User user = JsonUtil.jsonParse(User.class, JsonUtil.parseJson(jwtUser.getUser()));
                try{
                    if(token.equals(getRedisCashToke(user.getId()))){
                        return false;
                    }else {
                        setLoginCookie("");
                    }
                }catch (Exception e){
                    log.error("redis取值异常",e);
                }
            }
        }
        return true;
    }

    public long getRoleId(){
        long roleId = 1;
        User user = getUser();
        val userRoleOptional = userRoleRepository.findTop1ByUserIdAndExpireTimeGreaterThanEqualOrderByRoleIdDesc(user.getParentId() == 0 ?user.getId():user.getParentId(), new Date());

        if(userRoleOptional.isPresent()){
            roleId = userRoleOptional.get().getRoleId();
        }
        return roleId;
    }

    public void setLoginCookie(String data) {
        Cookie cookie = new Cookie(authorized, data);
        cookie.setPath("/");
        cookie.setMaxAge(7200);
        cookie.setDomain(domain);
        HttpUtil.getResponse().addCookie(cookie);
        Cookie cookie2 = new Cookie(authorized, data);
        cookie2.setPath("/");
        cookie2.setMaxAge(7200);
        cookie2.setDomain("xiguaji.com");
        HttpUtil.getResponse().addCookie(cookie2);
    }

    public String getRedisCashToke(long userId){
        return redisTemplate.opsForValue().get(String.valueOf(userId));
    }

    /**
     * 加密
     * @param userId
     * @return
     */
    public String encrypt(long userId) {
        return DESEncryptUtil.encrypt(String.valueOf(userId),authorized);
    }

    /**
     * 解密
     * @param code
     * @return
     */
    public long decrypt(String code) {
        try{
            return Long.valueOf(DESEncryptUtil.desEncrypt(code,authorized));
        }catch (Exception e){
            return 0;
        }
    }
}
